<template>
  <div class="app_main">
    <div class="search_box">
      <el-form ref="searchForm" :inline="true" :model="searchForm" size="mini">
        <search-form-box :show-more-btn="false">
          <template slot="showSearch">
            <el-form-item label="规格名称" prop="name">
              <el-input v-model="searchForm.name" placeholder="请输入规格名称" clearable/>
            </el-form-item>
            <el-form-item label="关联的媒体类型" prop="mediaTypeId">
              <el-select v-model="searchForm.mediaTypeId" filterable style="width: 100%" clearable
                         placeholder="请选择媒体类型"
              >
                <el-option v-for="(item,index) in mediaTypeArr" :key="index" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </template>
          <template slot="searchBtn">
            <el-form-item>
              <el-button size="mini" type="primary" plain @click="search">查询</el-button>
              <el-button size="mini" type="info" plain @click="resetForm('searchForm')">重置</el-button>
            </el-form-item>
          </template>
        </search-form-box>
      </el-form>
    </div>
    <el-row style="margin-bottom: 10px">
      <el-button size="mini" type="primary" @click="add">新增规格</el-button>
    </el-row>
    <div class="data_box">
      <el-table v-loading="tableLoading" :data="tableData" stripe border size="mini">
        <el-table-column fixed="left" width="50" type="index" label="序号" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="规格名称" min-width="200" prop="name" align="center"/>
        <el-table-column label="关联媒体类型名称" min-width="200" prop="media_type_name" align="center"/>
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button-group>
              <el-button icon="el-icon-view" size="mini" @click="lookPrice(scope.row)">查看价格配置</el-button>
              <el-button icon="el-icon-edit" type="primary" size="mini" @click="editRow(scope.row)">修改</el-button>
              <el-button icon="el-icon-delete" type="danger" size="mini" @click="remove(scope.row.id)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="searchForm.page"
      :page-sizes="[10,20,50,100, 200, 400]"
      :page-size.sync="searchForm.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <el-dialog :title="edit ? '修改规格' : '新增规格'" :visible.sync="cuFormDialogVisible" width="30%" center
               @close="closeCuFormDialog"
    >
      <el-form ref="cuForm" :model="cuForm" size="mini" :rules="rules" label-width="120px">
        <el-row :gutter="20" style="margin-left: -70px">
          <el-col :span="edit ? 24 : 12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="cuForm.name" placeholder="请输入规格名称"/>
            </el-form-item>
          </el-col>
          <el-col v-show="!edit" :span="12">
            <el-form-item label="所属媒体类型" prop="media_type_id">
              <el-select v-model="cuForm.media_type_id" style="width: 100%" clearable placeholder="请选择媒体类型">
                <el-option v-for="(item,index) in mediaTypeArr" :key="index" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="cuFormDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!--价格配置-->
    <el-dialog :title="tmpSpecName+'价格配置'" :visible.sync="lookPriceDialogVisible" width="70%" center
               @close="closePriceTableDialog"
    >
      <div v-loading="lookPriceDialogLoading">
        <el-row style="margin-bottom: 10px">
          <el-tooltip v-if="!mediaTypeConfig.has_multiple_spec && lookPriceTableTotal>=1" class="item" effect="dark"
                      content="此规格的媒体类型只能有一个价格配置" placement="top-start"
          >
            <div style="display: inline-block">
              <el-button size="mini" type="primary"
                         :disabled="!mediaTypeConfig.has_multiple_spec&&lookPriceTableTotal>=1"
                         @click="addPrice"
              >
                新增价格配置
              </el-button>
            </div>
          </el-tooltip>
          <el-button v-else size="mini" type="primary" @click="addPrice">新增价格配置</el-button>
        </el-row>
        <div class="data_box">
          <el-table :data="lookPriceTableData" stripe border size="mini">
            <el-table-column fixed="left" width="50" type="index" label="序号" align="center">
              <template slot-scope="scope">
                <span>{{ scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="价格名称" min-width="200" prop="name" align="center">
              <template slot-scope="scope">
                <span>{{ getPriceName(scope.row) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="mediaTypeConfig.has_duration_and_times" label="时长" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.duration + '秒' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="mediaTypeConfig.has_duration_and_times" label="次数" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.times + '次' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="mediaTypeConfig.has_price_day" label="天价格" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.price_day + '元' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="mediaTypeConfig.has_price_week" label="周价格" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.price_week + '元' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="mediaTypeConfig.has_price_month" label="月价格" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.price_month + '元' }}</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button-group>
                  <el-button icon="el-icon-edit" type="primary" size="mini" @click="editPrice(scope.row)">修改</el-button>
                  <el-button icon="el-icon-delete" type="danger" size="mini" @click="priceRemove(scope.row.id)">删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-pagination
          @size-change="handlePriceTableSizeChange"
          @current-change="handlePriceTableCurrentChange"
          :current-page="priceListParams.page"
          :page-sizes="[10,20,50,100, 200, 400]"
          :page-size="priceListParams.page_size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="lookPriceTableTotal"
        >
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="lookPriceDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!--价格表单-->
    <el-dialog :title="priceEdit?'修改价格配置':'添加价格配置'" :visible.sync="priceFormDialogVisible" width="30%" center
               append-to-body @close="closePriceFormDialog"
    >
      <el-form ref="priceForm" :model="priceForm" size="mini" label-width="100px" :rules="priceFormRules">
        <el-row>
          <el-col v-if="mediaTypeConfig.has_duration_and_times" :span="12">
            <el-form-item label="次数" prop="times">
              <el-input-number v-model="priceForm.times" style="width: 100%" :min="1" :step="1" step-strictly
                               :controls="false"
                               placeholder="请输入次数"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col v-if="mediaTypeConfig.has_duration_and_times" :span="12">
            <el-form-item label="时长" prop="duration">
              <el-input v-model="priceForm.duration" type="number" step="1" placeholder="请输入时长">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="mediaTypeConfig.has_price_day" label="天价格" prop="price_day">
              <el-input v-model="priceForm.price_day" type="number" step="0.01" placeholder="请输入天价格">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="mediaTypeConfig.has_price_week" label="周价格" prop="price_week">
              <el-input v-model="priceForm.price_week" type="number" step="0.01" placeholder="请输入周价格">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item v-if="mediaTypeConfig.has_price_month" label="月价格" prop="price_month">
              <el-input v-model="priceForm.price_month" type="number" step="0.01" placeholder="请输入月价格">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="priceForm.sort" type="number" step="0.01" placeholder="请输入排序"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="priceFormDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitPrice">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SearchFormBox from '@/components/SearchFormBox'
import common from '@/utils/common'
import { list, remove, submit } from '@/api/system/specs_manage'
import { all, detail } from '@/api/system/media_type'
import { list as priceList, save, edit, remove as priceRemove } from '@/api/system/media_type_spec_price'

export default {
  name: 'SpecsManage',
  components: { SearchFormBox },
  data() {
    return {
      tableData: [],
      tableLoading: false,
      listParams: {
        name: null,
        mediaTypeId: null,
        page_size: 10,
        page: 1
      },
      searchForm: {
        name: null,
        mediaTypeId: null,
        page_size: 10,
        page: 1
      },
      edit: false,
      cuFormDialogVisible: false,
      cuForm: {
        id: null,
        media_type_id: null,
        name: null,
        price_day: null,
        price_week: null,
        price_month: null
      },
      tmpMediaType: {},
      rules: {
        name: [
          { required: true, message: '请输入规格名称', trigger: 'blur' }
        ],
        media_type_id: [
          { required: true, message: '请选择关联的媒体类型', trigger: 'change' }
        ]
      },
      total: 0,
      mediaTypeArr: [],
      lookPriceDialogVisible: false,
      lookPriceTableData: [],
      lookPriceDialogLoading: false,
      lookPriceTableTotal: 0,
      priceForm: {
        id: null,
        duration: undefined,
        times: undefined,
        media_type_spec_id: null,
        price_day: null,
        price_week: null,
        price_month: null,
        sort: 1
      },
      priceFormRules: {
        duration: [
          { required: true, message: '请输入时长', trigger: 'blur' }
        ],
        times: [
          { required: true, message: '请输入次数', trigger: 'blur' }
        ],
        price_day: [
          { required: true, message: '请输入天价格', trigger: 'blur' }
        ],
        price_week: [
          { required: true, message: '请输入周价格', trigger: 'blur' }
        ],
        price_month: [
          { required: true, message: '请输入月价格', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' }
        ]
      },
      mediaTypeConfig: {
        has_duration_and_times: false,
        has_price_day: false,
        has_price_week: false,
        has_price_month: false,
        has_multiple_spec: false
      },
      priceListParams: {
        media_type_spec_id: null,
        page_size: 10,
        page: 1
      },
      priceEdit: false,
      priceFormDialogVisible: false,
      tmpSpecName: ''
    }
  },
  created() {
    this.getList()
    this.getMediaTypeArr()
  },
  methods: {
    getList() {
      this.tableLoading = true
      list(this.listParams).then(res => {
        this.tableLoading = false
        this.total = res.data.total
        this.tableData = res.data.records.map(item => {
          if (item.media_type_name === null) {
            item.media_type_name = '全部'
          }
          return item
        })
      }).catch(() => {
        this.tableLoading = false
      })
    },
    search() {
      this.searchForm.page = 1
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    async remove(id) {
      let flag = await common.confirmDialog('您确定删除吗')
      if (flag) {
        const loading = this.$loading({
          lock: true,
          text: '提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        remove({ id }).then(res => {
          this.$message.success('操作成功')
          loading.close()
          this.getList()
        }).catch(() => {
          loading.close()
        })
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.listParams = Object.assign({}, this.searchForm)
      this.getList()
    },
    add() {
      this.cuFormDialogVisible = true
    },
    editRow(row) {
      this.cuFormDialogVisible = true
      this.edit = true
      this.cuForm = Object.assign({}, row)
    },
    submit() {
      this.$refs.cuForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          submit(this.cuForm).then(res => {
            this.$message.success('操作成功')
            loading.close()
            this.getList()
            this.cuFormDialogVisible = false
          }).catch(() => {
            loading.close()
          })
        }
      })
    },
    closeCuFormDialog() {
      this.cuForm = {
        id: null,
        media_type_id: null,
        name: null,
        duration: undefined,
        times: undefined,
        price_day: null,
        price_month: null
      }
      this.edit = false
      this.$nextTick(() => {
        this.$refs.cuForm.clearValidate()
      })
    },
    handleSizeChange(val) {
      this.listParams.page_size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listParams.page = val
      this.getList()
    },
    getMediaTypeArr() {
      all().then(res => {
        this.mediaTypeArr = res.data
      })
    },
    lookPrice(row) {
      this.lookPriceDialogLoading = true
      this.priceListParams.media_type_spec_id = row.id
      this.priceForm.media_type_spec_id = row.id
      this.tmpSpecName = row.name
      this.getMediaTypeConfig(row.media_type_id)
      this.lookPriceDialogVisible = true
    },
    /**
     * 获取媒体类型配置
     */
    getMediaTypeConfig(id) {
      detail({ id }).then(res => {
        this.mediaTypeConfig = res.data
        this.getPriceList()
      })
    },
    getPriceName(row) {
      if (row) {
        if (this.mediaTypeConfig.has_duration_and_times) {
          return this.tmpSpecName + '(' + row.duration + '秒/' + row.times + '次)'
        } else {
          return this.tmpSpecName
        }
      } else {
        return ''
      }
    },
    addPrice() {
      this.priceFormDialogVisible = true
    },
    editPrice(row) {
      this.priceForm = Object.assign({}, row)
      this.priceEdit = true
      this.priceFormDialogVisible = true
    },
    handlePriceTableSizeChange(val) {
      this.priceListParams.page_size = val
      this.getPriceList()
    },
    handlePriceTableCurrentChange(val) {
      this.priceListParams.page = val
      this.getPriceList()
    },
    closePriceFormDialog() {
      this.$refs.priceForm.clearValidate()
      this.priceEdit = false
      this.priceForm = Object.assign(this.priceForm, {
        id: null,
        duration: undefined,
        times: undefined,
        price_day: null,
        price_week: null,
        price_month: null,
        sort: 1
      })
    },
    closePriceTableDialog() {
      this.tmpSpecName = ''
      this.mediaTypeConfig = {
        has_duration_and_times: false,
        has_price_day: false,
        has_price_week: false,
        has_price_month: false,
        has_multiple_spec: false
      }
      this.priceListParams = {
        media_type_spec_id: null,
        page_size: 10,
        page: 1
      }
      this.priceForm.media_type_spec_id = null
    },
    getPriceList() {
      this.lookPriceDialogLoading = true
      priceList(this.priceListParams).then(res => {
        this.lookPriceTableData = res.data.records
        this.lookPriceTableTotal = res.data.total
        this.lookPriceDialogLoading = false
      })
    },
    submitPrice() {
      this.$refs.priceForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '提交中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          if (this.priceEdit) {
            edit(this.priceForm).then(res => {
              this.$message.success('操作成功')
              loading.close()
              this.getPriceList()
              this.priceFormDialogVisible = false
            }).catch(() => {
              loading.close()
            })
          } else {
            save(this.priceForm).then(res => {
              this.$message.success('操作成功')
              loading.close()
              this.getPriceList()
              this.priceFormDialogVisible = false
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    },
    async priceRemove(id) {
      let flag = await common.confirmDialog('您确定删除吗')
      if (flag) {
        const loading = this.$loading({
          lock: true,
          text: '提交中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        priceRemove({ id }).then(res => {
          this.$message.success('操作成功')
          loading.close()
          this.getPriceList()
        }).catch(() => {
          loading.close()
        })
      }
    }
  }
}
</script>

<style scoped>
.app_main {
  padding: 20px 20px 0 20px;
}

/deep/ .el-input-number .el-input__inner {
  text-align: left;
}
</style>
